package no.spk.util.inforama.service.applicationserver.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import no.spk.util.inforama.service.applicationserver.ApplicationServerAnalyzer;
import no.spk.util.inforama.service.container.Container;
import no.spk.util.inforama.service.container.ContainerAnalyzer;
import no.spk.util.inforama.service.container.impl.ContainerAnalyzerImpl;
import no.spk.util.inforama.service.container.impl.ContainerImpl;
import no.spk.util.inforama.service.deployable.Deployable;
import no.spk.util.inforama.service.factory.impl.DeployableFactoryImpl;
/**
 * @author Marius
 */
public class ApplicationServerAnalyzerImpl implements ApplicationServerAnalyzer {

	private String rootPath;

	public List<Container> createContainers() {
		List<Container> containerList = new ArrayList<Container>();
		for (File directory : getContainerDirectories()) {
			if ( !directory.isHidden() && directory.canRead() ) {
				containerList.add(createContainer(directory));				
			}
		}
		return containerList;
	}

	private Container createContainer(File directory) {
		Container container = new ContainerImpl(directory.getName(),directory.getAbsolutePath());
		ContainerAnalyzer ca = new ContainerAnalyzerImpl(new DeployableFactoryImpl(), directory.getAbsolutePath());
		List<Deployable> deployables = ca.getDeployables();
		container.setDeployables(deployables);
		return container;
	}

	private List<File> getContainerDirectories() {

		List<File> containerDirectories = new ArrayList<File>();
		for (File file : getFilesInRootPath()) {
			if (isDirectory(file)) {
				containerDirectories.add(file);
			}
		}

		return containerDirectories;
	}

	private File[] getFilesInRootPath() {
		File root = new File(rootPath);
		if (isDirectory(root)) {
			return root.listFiles();
		}
		throw new RuntimeException("rootPath is not set to a directory");
	}

	private boolean isDirectory(File path) {
		return path != null && path.isDirectory();
	}

	public void setRootPath(String rootPath) {
		this.rootPath = rootPath;
	}
}
